package dream.web;

import com.alibaba.fastjson.JSON;
import dream.pojo.Article;
import dream.pojo.User;
import dream.service.ArticleService;
import dream.util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/googleIn")
public class GoogleInCollectServlet extends HttpServlet {
    private ArticleService articleService = new ArticleService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询所有博客，判断是否为用户收藏的文章，时间消耗较高，但由于没有单独存储用户收藏文章的详细信息，所以考虑此方法
        String val = req.getParameter("val");
        List<Article> articles = articleService.SelectByVal(val);

        User user = SessionUtils.getLoginUser(req);
        int[] aids = articleService.SelectCollectById(user.getId());

        if(aids == null){
            return;
        }

        List<Article> articles1 = new ArrayList<>();
        for(Article article :articles){
            int flag = 0;
            for (int i :aids){
                if(i == article.getAid()){
                    flag = 1;
                }
            }
            if(flag == 1){
                articles1.add(article);
            }
        }

        String jsonString = JSON.toJSONString(articles1);
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(jsonString);
    }
}
